package com.cxg.fairy.ec.main.personal.applyInvoice;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.ScrollView;

import com.alibaba.fastjson.JSON;
import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.toasty.Toasty;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.rengwuxian.materialedittext.MaterialEditText;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/3/8.
 */

public class ApplyInvoiceDelegate extends LatteDelegate implements ISuccess {

    @BindView(R2.id.ms_invoice_spinner)
    MaterialSpinner mMaterialSpinner = null;

    @BindView(R2.id.met_business_license)
    MaterialEditText mBusinessLicense = null;

    @BindView(R2.id.met_id_taxpayer)
    MaterialEditText mTaxPayer = null;

    @BindView(R2.id.met_reg_address)
    MaterialEditText mRegAddress = null;

    @BindView(R2.id.met_reg_phone)
    MaterialEditText mRegPhone = null;

    @BindView(R2.id.met_invoice_first_date)
    MaterialEditText mInvoiceDate = null;

    @BindView(R2.id.met_invoice_email)
    MaterialEditText mInvoiceEmail = null;

    @BindView(R2.id.met_invoice_bank_no)
    MaterialEditText mInvoiceBankNo = null;

    @BindView(R2.id.met_invoice_bank)
    MaterialEditText mInvoiceBankName = null;

    @BindView(R2.id.ms_invoice_period_root)
    MaterialSpinner mInvoicePeriodRoot = null;

    @BindView(R2.id.scrollView_invoice)
    ScrollView mScrollView = null;

    @Override
    public Object setLayout() {
        return R.layout.delegate_apply_invoice;
    }

    @OnClick(R2.id.back_home)
    void onClickBackHome() {
        getSupportDelegate().pop();
    }

    @OnClick(R2.id.btn_apply_invoice)
    void onClickApplyInvoice() {
        if (checkForm()) {
            RestClient.builder().url("applyForInvoice")
                    .params("uuid", AccountManager.getSignUUID())
                    .params("invoice_type", mMaterialSpinner.getText())
                    .params("biz_license", mBusinessLicense.getText())
                    .params("taxpayer_no", mTaxPayer.getText())
                    .params("address", mRegAddress.getText())
                    .params("com_tel", mRegPhone.getText())
                    .params("deposit_bank", mInvoiceBankName.getText())
                    .params("bank_account", mInvoiceBankNo.getText())
                    .params("receip_cycle", mInvoicePeriodRoot.getText())
                    .params("receip_date_first", mInvoiceDate.getText())
                    .params("email", mInvoiceEmail.getText())
                    .loader(getContext())
                    .success(this)
                    .build()
                    .post();
        } else {
            Toasty.error(getContext(), "表单数据有误!请检查后重新提交!").show();
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        final Window w = this.getSupportDelegate().getActivity().getWindow();
        scrollUp(mInvoiceEmail,w);
        scrollUp(mInvoiceBankName,w);
        scrollUp(mInvoiceBankNo,w);

        //开票类型
        mMaterialSpinner.setItems(getResources().getStringArray(R.array.invoice_types));
        mMaterialSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
//                Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
            }
        });

        //周期Root
        mInvoicePeriodRoot.setItems(getResources().getStringArray(R.array.invoice_period_root));
        mInvoicePeriodRoot.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
//                Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();

            }
        });

        mInvoiceDate.setInputType(InputType.TYPE_NULL);

        mInvoiceDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                if(hasFocus){
                    showDatePickerDialog();
                }
            }
        });

        mInvoiceDate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDatePickerDialog();
            }
        });
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onSuccess(String response) {
        int code = JSON.parseObject(response).getInteger("code");
        if (code == 1) {
            Toasty.success(getContext(), "发票申请成功!").show();
        } else if (code == 0) {
            Toasty.error(getContext(), "发票申请失败!请联系管理员!").show();
        }
    }

    public void showDatePickerDialog() {
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // TODO Auto-generated method stub
                mInvoiceDate.setText(year+"/"+(monthOfYear+1)+"/"+dayOfMonth);
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();

    }

    public void scrollUp(MaterialEditText met,final Window w) {
        met.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                w.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                DisplayMetrics outMetrics = new DisplayMetrics();
                w.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
                int wHeight = outMetrics.heightPixels;
                int vHeight = mScrollView.getChildAt(0).getMeasuredHeight();
                mScrollView.scrollTo(0,(vHeight-wHeight)*2/3);
                return false;
            }
        });
    }

    private boolean checkForm() {
        String mspinner = mMaterialSpinner.getText().toString();
        String mBusinessL = mBusinessLicense.getText().toString();
        String mTpayer = mTaxPayer.getText().toString();
        String mRegAdd = mRegAddress.getText().toString();
        String mRegP = mRegPhone.getText().toString();
        String mInvoiceD= mInvoiceDate.getText().toString();
        String mInvoiceE = mInvoiceEmail.getText().toString();
        String mInvoiceBn0 = mInvoiceBankNo.getText().toString();
        String mInvoiceBname = mInvoiceBankName.getText().toString();
        String mInvoicepr = mInvoicePeriodRoot.getText().toString();
        if (mspinner.length() < 4 || mBusinessL.length() < 4 || mTpayer.length() < 4 || mRegAdd.length() < 4 || mRegP.length() < 4 || mInvoiceD.length() < 4 || mInvoiceE.length() < 4 || mInvoiceBn0.length() < 4 || mInvoiceBname.length() < 4 || mInvoicepr.length() < 4) {
            return false;
        } else {
            return true;
        }
    }

}
